<template>
  <div>
    <el-dialog title="开票管理" v-model="showDialog" :width="dialogWidth" :close-on-click-modal="false">
      <div class="bigTitle">开票管理</div>
      <el-form label-width="120px" class="baseForm" :rules="rules" :model="form" ref="baseForm">
        <el-form-item label="开票名称" class="item" prop="name">
          <el-input v-model="form.name" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="开票日期" class="item" prop="invoiceDate">
          <el-date-picker v-model="form.invoiceDate" type="date" value-format="YYYY-MM-DD" placeholder="选择收款日期" />
        </el-form-item>
        <el-form-item label="客户名称" class="item" prop="customerName">
          <el-input v-model="form.customerName" class="form-input" @focus="checkCustomer"></el-input>
        </el-form-item>
        <el-form-item label="发票类型" class="item" prop="invoiceTypeId">
          <el-select v-model="form.invoiceTypeId" placeholder="请选择">
            <el-option v-for="item in types" :key="item.id" v-key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票金额" class="item" prop="money">{{ form.money }}元</el-form-item>

        <el-form-item label="开票人" class="item" prop="tickerName">
          <el-input v-model="form.tickerName" class="form-input" @focus="checkSaler"></el-input>
        </el-form-item>
        <el-form-item label="归属部门" class="item" prop="orgId">
          <el-select v-model="form.orgId" placeholder="请选择">
            <el-option v-for="item in orgs" :key="item.id" v-key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="纳税人识别号" class="item" prop="taxNumber">
          <el-input v-model="form.taxNumber" class="form-input"></el-input>
        </el-form-item>
      </el-form>
      <div class="bigTitle">发票产品信息</div>
      <el-table :data="tables" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column prop="productCode" label="产品编号" width="100"></el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="price" label="产品单价" width="100" :formatter="priceformatter"></el-table-column>
        <el-table-column prop="productSpec" label="产品规格" width="100"></el-table-column>
        <el-table-column label="产品数量" width="180">
          <template #default="scope">
            <el-input type="number" v-model="scope.row.productCount" @change="changeProductRow(scope.row)">
              <template #append>{{ scope.row.productUnit }}</template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="总金额" :formatter="(...arr) => arr[2] + '元'"></el-table-column>
        <el-table-column label="" width="60">
          <template #default="scope">
            <el-button icon="el-icon-remove" @click.stop="removeClick(scope.index)" size="mini"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click.stop="create_productClick">添加产品</el-button>
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveAddClick">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <dialog-customer ref="r_customer"></dialog-customer>
    <dialog-saler ref="r_saler"></dialog-saler>
    <dialog-product ref="r_product"></dialog-product>
  </div>
</template>
<script>
import DialogCustomer from '../../components/dialog_customer.vue'
import DialogSaler from '../../components/dialog_saler.vue'
import DialogProduct from '../../components/dialog_product.vue'
const defaultdata = {
  name: '',
  invoiceDate: '',
  customerId: 0,
  customerName: '',
  invoiceTypeId: 0,
  invoiceTypeName: '',
  money: 0,
  tickerId: 0,
  tickerName: '',
  orgId: 0,
  orgName: '',
  taxNumber: '',
}
const rules = {
  name: [{ required: true, message: '请输入开票名称', trigger: 'blur' }],
  invoiceDate: [{ required: true, message: '请选择开票日期', trigger: 'blur' }],
  customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
  invoiceTypeId: [
    {
      required: true,
      validator(_, value, callback) {
        if (value <= 0) return callback(new Error('请选择开票类型'))
        callback()
      },
    },
  ],
  tickerName: [{ required: true, message: '请选择开票人', trigger: 'change' }],
  orgId: [
    {
      required: true,
      validator(_, value, callback) {
        if (+value <= 0) return callback(new Error('请选择归属部门'))
        callback()
      },
      trigger: 'change',
    },
  ],
}
export default {
  components: { DialogCustomer, DialogSaler, DialogProduct },
  data() {
    return {
      form: Object.assign({}, defaultdata),
      showDialog: false,
      dialogWidth: window.innerWidth > 768 ? '80%' : '100%',
      rules,
      products: [],
      filemsgs: [],
      types: [],
      tables: [],
    }
  },
  watch: {
    tables: {
      handler() {
        var money = this.tables.reduce((a, b) => a + b.money, 0)
        this.form.money = money
      },
      deep: true,
    },
  },
  methods: {
    saveAddClick() {
      this.$refs.baseForm.validate((v) => {
        if (!v) return
        if (this.tables.length == 0) return this.$message.warning('请选择产品信息')
        const form = Object.assign({}, this.form)
        form.products = this.tables
        this.$api.invoice.update(form).then(({ state, msg }) => {
          if (!state) return this.$message.warning(msg)
          this.showDialog = false
          this.$emit('search')
        })
      })
    },
    create_contractClick() {},
    removeClick(index) {
      this.tables.splice(index, 1)
    },
    show(row) {
      this.tables = []
      this.form = Object.assign({}, defaultdata, row || {})
      this.showDialog = true
    },
    checkCustomer({ target }) {
      target.blur()
      this.$refs.r_customer.show().then(({ id, name }) => {
        this.form.customerId = id
        this.form.customerName = name
      })
    },
    checkSaler({ target }) {
      target.blur()
      this.$refs.r_saler.show().then(({ id, name }) => {
        this.form.tickerId = id
        this.form.tickerName = name
      })
    },
    create_productClick() {
      this.$refs.r_product.show().then((data) => {
        this.tables.push({
          productId: data.id,
          productName: data.name,
          productCode: data.code,
          productSpec: data.spec,
          projectName: '',
          price: data.money,
          productUnit: data.unit,
          productCount: 1,
          money: data.money,
        })
      })
    },
    changeProductRow(row) {
      var money = +row.productCount * +row.price
      row.money = money
    },
    priceformatter(...arr) {
      const unit = arr[0].productUnit
      return arr[2] + '元' + (unit ? `/${unit}` : '')
    },
  },
  mounted() {
    this.$api.dictionary.enums(5).then(({ msg }) => {
      this.types = msg
    })
    this.$api.dictionary.enums(3).then(({ msg }) => {
      this.orgs = msg
    })
  },
}
</script>
<style lang="scss" scoped>
@media (max-width: 778px) {
  .baseForm {
    display: grid;
    grid-template-columns: repeat(1, 1fr);
  }
}
@media (min-width: 778px) {
  .baseForm {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
  }
}

.bigTitle {
  font-size: 18px;
  text-indent: 40px;
  padding: 20px 0;
  font-weight: bold;
  border-bottom: 1px solid #ddd;
  margin-bottom: 10px;
  background: #00000005;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
</style>
